from . import blue
from apps.users.models import User
from flask import request
from flask.views import MethodView
from common.json_response import JsonResponse
from common.status_code import StatusCode
import jwt
from datetime import datetime, timedelta
from config import SECRET_KEY

class AuthView(MethodView):
    def post(self):
        """用户登录"""
        try:
            data = request.get_json()
            if not data:
                return JsonResponse.error(
                    message="请求数据不能为空",
                    status=StatusCode.BAD_REQUEST.value
                )

            username = data.get('username')
            password = data.get('password')
            
            if not username or not password:
                return JsonResponse.error(
                    message="用户名和密码不能为空",
                    status=StatusCode.BAD_REQUEST.value
                )

            user = User.query.filter_by(name=username).first()
            
            if not user or not user.check_password(password):
                return JsonResponse.error(
                    message="用户名或密码错误",
                    status=StatusCode.UNAUTHORIZED.value
                )

            # 生成JWT token
            token = jwt.encode({
                'user_id': user.id,
                'exp': datetime.utcnow() + timedelta(days=7)
            }, SECRET_KEY, algorithm='HS256')

            response = JsonResponse.success(
                data={'user_id': user.id, 'username': user.name},
                message="登录成功"
            )
            
            # 设置cookie
            response.set_cookie(
                'user_token',
                token,
                max_age=7*24*60*60,  # 7天过期
                httponly=True,
                samesite='Lax'
            )
            
            return response
        except Exception as e:
            return JsonResponse.error(
                message=str(e),
                status=StatusCode.INTERNAL_SERVER_ERROR.value
            )

    def delete(self):
        """用户登出"""
        try:
            response = JsonResponse.success(message="退出成功")
            response.delete_cookie('user_token')
            return response
        except Exception as e:
            return JsonResponse.error(
                message=str(e),
                status=StatusCode.INTERNAL_SERVER_ERROR.value
            )

# 注册路由
auth_view = AuthView.as_view('auth_api')
blue.add_url_rule('/login', view_func=auth_view, methods=['POST'])
blue.add_url_rule('/logout', view_func=auth_view, methods=['DELETE'])